package com.PTRS.servlet;

import com.PTRS.dao.IUserDao;
import com.PTRS.entities.User;
import com.PTRS.test.DBHelper;
import com.alibaba.fastjson.JSON;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    private static final long serialVersionID = 1L;

    public String createUserID(String userTel){
        Calendar calendar = Calendar.getInstance();
        String uid = "root";
        if (!userTel.equals("root")){
            if (userTel.substring(0,1).equals("T")){
                uid = "PT" + calendar.get(Calendar.YEAR) + userTel.substring(7);
            }
            else {
                uid = "CU" + calendar.get(Calendar.YEAR) + userTel.substring(7);
            }
        }

        return uid;
    }

    public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String userNickname = httpServletRequest.getParameter("nikename");
        String userPasswd = httpServletRequest.getParameter("passwd");
        String userEmail = httpServletRequest.getParameter("email");
        String userTel = httpServletRequest.getParameter("tel");
        String userID = createUserID(userTel);
        DBHelper helper = new DBHelper();
        User user = new User();
        user.setUserID(userID);
        user.setUserPasswd(userPasswd);
        user.setUserNickname(userNickname);
        user.setUserEmail(userEmail);
        user.setUserTel(userTel);
        boolean result = false;

        IUserDao userDao = helper.init();
        userDao.saveUser(user);
        User user1 = userDao.findUserByID("userID");
        if (user1.getUserNickname() != null){
            result = true;
            String objStr = JSON.toJSONString(result);
            try {
                PrintWriter printWriter = httpServletResponse.getWriter();
                printWriter.print(objStr);
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        helper.destory();
    }
}
